package oop.ex3.filemanager.actions;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.LinkedHashSet;

import oop.ex3.messages.SimpleMessage;
import oop.ex3.messages.ValidHeaders;
import oop.ex3.messages.exception.InvalidHeaderException;
import oop.ex3.messages.exception.UnexpectedMessageEndException;

import oop.ex3.filemanager.FMContext;
import oop.ex3.filemanager.actions.exceptions.RecievedError;
import oop.ex3.nameserver.exception.UnexpectedMessageException;
import oop.ex3.sockets.ClientSocket;

public class FireAllServers extends FmAction {

	/**
	 * constructor for FireAllServers action
	 * @param context
	 */
	public FireAllServers(FMContext context) {
		super(context);
	}

	/**
	 * send GOAWAY messages to all servers
	 * @param params - array of command parrams
	 */
	public void run(String[] params) {
		LinkedHashSet<InetSocketAddress> servers = _context.getServersSet();
		for (InetSocketAddress server : servers){
			try {
				ClientSocket socket = new ClientSocket(new 
						InetSocketAddress(server.getAddress(), server.getPort()));
				try {
					performHandShake(socket);
					socket.SendMessage(new SimpleMessage(ValidHeaders.GOAWAY));
					waitForDone(socket);
					finishSession(socket);
					socket.closeClientSocket();
				} catch (UnexpectedMessageEndException e) {
					finishSession(socket);
					socket.closeClientSocket();
				} catch (UnexpectedMessageException e) {
					finishSession(socket);
					socket.closeClientSocket();
				} catch (RecievedError e) {
					finishSession(socket);
					socket.closeClientSocket();
				} catch (InvalidHeaderException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (IOException e) {

			} 
		}
		
	}

}
